package com.ruoyi.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.CustomData;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.domain.vo.SelectOptionVO;
import com.ruoyi.common.core.mapper.CustomDataMapper;
import com.ruoyi.common.core.mapper.SysDeptMapper;
import com.ruoyi.common.core.service.BaseServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mapper.SysDictDataMapper;
import com.ruoyi.mapper.SysDictTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
import static com.ruoyi.common.utils.sql.SqlUtil.formatSql;
import static com.ruoyi.service.SysUserServiceImpl.addSystemParam;
import static com.ruoyi.service.SysUserServiceImpl.dataScopeFilter;

/**
 * 字典 业务层处理
 */
@Service
public class SysDictTypeServiceImpl extends BaseServiceImpl<SysDictTypeMapper, SysDictType> {
    @Autowired
    private SysDictTypeMapper dictTypeMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private CustomDataMapper customDataMapper;


    /**
     * 项目启动时，初始化字典到缓存
     */
    public void init() {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */

    public List<SysDictType> selectDictTypeList(SysDictType dictType) {
        return dictTypeMapper.selectDictTypeList(dictType);
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */

    public List<SysDictType> selectDictTypeAll() {
        return dictTypeMapper.selectDictTypeAll();
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */

    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        dictDatas = dictDataMapper.selectDictDataByType(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */

    public SysDictType selectDictTypeById(Long dictId) {
        return dictTypeMapper.selectDictTypeById(dictId);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */

    public SysDictType selectDictTypeByType(String dictType) {
        return dictTypeMapper.selectDictTypeByType(dictType);
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     */

    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = selectDictTypeById(dictId);
            if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            dictTypeMapper.deleteDictTypeById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */

    public void loadingDictCache() {
        SysDictData dictData = new SysDictData();
        dictData.setStatus("0");
        Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 清空字典缓存数据
     */

    public void clearDictCache() {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */

    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */

    public int insertDictType(SysDictType dict) {
        dict.insert();
        DictUtils.setDictCache(dict.getDictType(), null);
        return 1;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */

    @Transactional
    public int updateDictType(SysDictType dict) {
        SysDictType oldDict = dictTypeMapper.selectDictTypeById(dict.getDictId());
        dictDataMapper.updateDictDataType(oldDict.getDictType(), dict.getDictType());
        int row = dictTypeMapper.updateDictType(dict);
        if (row > 0) {
            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(dict.getDictType());
            DictUtils.setDictCache(dict.getDictType(), dictDatas);
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */

    public boolean checkDictTypeUnique(SysDictType dict) {
        Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
        if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**增加内置系统参数*/

    /**
     * 获取下拉框Option. 支持3种不同的方式。
     * 1、通过SYS_CUSTOM_DATA 表 sql 配置
     * 如果ID中包含TREE，则为树结构。必须字段id、name、parent_id
     * 如果为普通列表，则需要返回label、value
     * 2、通过字典表配置SYS_DICT
     * 3、通过Java代码实现
     */
    public Object getDictSelectOptions(Map<String, Object> param) {
        addSystemParam(param);

        String dictType = (String) param.get("dictType");
        if("SQLID_ROLE_SELECT".equals(dictType)){
            param.put("dataScope",dataScopeFilter("t1", "t1"));
        }

        CustomData customData = customDataMapper.getByDataName(dictType);
        if (customData != null) {
            String sql = formatSql(customData.getQuerySql(), param);
            List<LinkedHashMap> dataList = dictDataMapper.selectBySql(sql);
            if (customData.isTree()) {
                List tree = TreeUtil.build(dataList, findRootId(dataList), new TreeNodeConfig(),
                        (object, treeNode) -> {
                            treeNode.putAll(JSON.parseObject(JSON.toJSONString(object)));
                        });
                if (tree == null) {
                    tree = new ArrayList();
                }
                return tree;
            } else {
                return dataList;
            }
        } else if (dictType.startsWith("DEPT_SELECT_TREE")) {
            return getDeptSelectTree();
        } else if (dictType.startsWith("SELF_AND_SUBORDINATE_DEPT_TREE")) { //自己部门以及下属部门
            return getSelfAndSubordinateDeptTree();
        } else {
            List<SysDictData> dictList = dictDataMapper.selectDictDataByType(dictType);
            List<SelectOptionVO> selectOptionList = dictList.stream().map(r -> {
                return new SelectOptionVO(r.getDictLabel(), r.getDictValue());
            }).collect(Collectors.toList());
            return selectOptionList;
        }

    }

    public String findRootId(List<LinkedHashMap> dataList) {
        dataList.stream().forEach(row -> {
            row.put("id", row.get("id").toString());
            row.put("parentId", row.get("parentId").toString());
        });
        List<String> ids = dataList.stream().map(r1 -> r1.get("id").toString()).collect(Collectors.toList());
        LinkedHashMap root = dataList.stream().filter(r -> {
            return !ids.contains(r.get("parentId").toString());
        }).findAny().orElse(null);
        if (root == null) {
            return "0";
        } else {
            return (String) root.get("parentId");
        }
    }

    private Object getDeptSelectTree() {
        List<SysDept> deptList = deptMapper.selectAllDeptListByParentId(0L);
        List<Tree<Long>> tree = TreeUtil.build(deptList, 0L, new TreeNodeConfig().setChildrenKey("children").setIdKey("deptId").setParentIdKey("parentId").setNameKey("deptName"),
                (vo, treeNode) -> {
                    treeNode.put("deptId", vo.getDeptId());
                    treeNode.put("value", vo.getDeptId());
                    treeNode.put("parentId", vo.getParentId());
                    treeNode.put("label", vo.getDeptName());
                });
        return tree;
    }

    private Object getSelfAndSubordinateDeptTree() {
        Long deptId = SecurityUtils.getDeptId();
        SysDept dept = deptMapper.selectDeptById(deptId);
        List<SysDept> deptList = deptMapper.selectChildrenAndSelfById(deptId);
        TreeNodeConfig config =  new TreeNodeConfig().setChildrenKey("children").setIdKey("deptId")
                .setParentIdKey("parentId").setNameKey("deptName");


        List<Tree<Long>> tree = TreeUtil.build(deptList, dept.getParentId(), config ,
                (vo, treeNode) -> {
                    treeNode.put("deptId", vo.getDeptId());
                    treeNode.put("value", vo.getDeptId());
                    treeNode.put("parentId", vo.getParentId());
                    treeNode.put("label", vo.getDeptName());
                });
        return tree;
    }


    public Object getDictTypeList() {
        List<SysDictType> deptList = dictTypeMapper.getDictTypeList();
        return deptList.stream().map(r -> MapUtil.builder().put("dictId", r.getDictId())
                .put("dictName", r.getDictName()).put("dictType", r.getDictType()).put("key", r.getDictId()).build()).collect(Collectors.toList());


    }

    public void doSave(SysDictType dict) {
        Assert.isFalse(!this.checkDictTypeUnique(dict), "新增字典'" + dict.getDictName() + "'失败，字典类型已存在");
        dict.insertOrUpdate();
    }

    public void doDelete(SysDictType dict) {
        dict = this.getById(dict.getDictId());
        dictDataMapper.deleteByType(dict.getDictType());
        dict.deleteById();
    }


    public void dictToConstant(String dictType) throws NoApiKeyException, InputRequiredException {
        Constants.apiKey = "sk-d301ad6ad5564a01ac2d64af645d0107";
        SysDictType dict = dictTypeMapper.selectDictTypeByType(dictType);
        if (dict != null) {
            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(dict.getDictType());
            dictDatas.stream().forEach(r -> {
                r.setDictTypeLabel(dict.getDictName());
            });
            StringBuilder code = new StringBuilder();
            code.append("/**\n");
            code.append(" * dictType = " + dict.getDictType() + "\n");
            code.append(" * " + dict.getDictName() + "\n");
            code.append("*/\n");
            code.append("interface  {\n");
            for (int i = 0; i < dictDatas.size(); i++) {
                SysDictData dictData = dictDatas.get(i);
                code.append("    /**" + dictData.getDictLabel() + "*/\n");
                code.append("    String  = \"" + dictData.getDictValue() + "\";\n");
            }
            code.append("}\n");
            String message = "将代码补充完整，不要自行发挥，就使用interface  ， 只返回代码: \n " + code;
            Generation gen = new Generation();
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content(message)
                    .build();
            GenerationParam param = GenerationParam.builder()
                    .model("qwen-turbo")
                    .messages(Arrays.asList(userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .topP(0.8)
                    .build();

            GenerationResult result = gen.call(param);
            String content = result.getOutput().getChoices().get(0).getMessage().getContent();
            System.out.println(content);
        }
    }
}
